package com.leyou.gateway.filters;

import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.PrivilegeTokenHolder;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理请求和响应的方法
 *
 * @version V1.0
 * @package com.leyou.gateway.interceptors
 * @description:
 * @author: pc
 * @date: 2019/7/12 10:43
 */
@Slf4j
@Component
public class PrivilegeFilter extends ZuulFilter {
    @Autowired
    private JwtProperties prop;

    @Autowired
    private PrivilegeTokenHolder tokenHolder;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取token
        String token = tokenHolder.getToken();
        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //添加请求头
        context.addZuulRequestHeader(prop.getApp().getHeaderName(), token);
        return null;
    }
}
